// =====================  proxy 监听对象开始  ======================
console.log('=====================  proxy 监听对象开始  ======================')

const person = {
    name: 'hhj',
    age: 18
};

const personProxy = new Proxy(person, {
    /**
     * 监听属性的访问
     * @param {*} target  当前代理的对象
     * @param {*} property  当前访问的key
     */
    get(target, property) {
        // return 100;
        return property in target ? target[property]: 'default';
    },
    /**
     * 监听属性的设置
     * @param {*} target  当前代理的对象
     * @param {*} property  当前设置的key
     * @param {*} value  当前访问的值
     */
    set(target, property, value) {
        if (property === 'age') {
            if (!Number.isInteger(value)) {
                throw new TypeError(`${property} is not an int`)
            }
        }
        target[property] = value;
    },
    /**
     * 删除一个熟悉
     * @param {*} target 
     * @param {*} property 
     */
    deleteProperty(target, property) {
        console.log('deleteProperty', property);
        delete target[property];
    }
});

// personProxy.age = 'age11';
personProxy.age = 19;

console.log('personProxy.name', personProxy.name);
console.log('personProxy.xxx', personProxy.xxx);

delete personProxy.age;

console.log('person', person);

console.log('=====================  proxy 监听对象结束  ======================')
// =====================  proxy 监听对象结束  ======================


// =====================  proxy 监听数组 开始  ======================
console.log('=====================  proxy 监听数组 开始  ======================')

const list = [];
const listProxy = new Proxy(list, {
    set(target, property, value) {
        console.log('set property', property, value);
        target[property] = value;
        return true;
    }
});

listProxy.push(100);


console.log('=====================  proxy 监听数组 结束  ======================')
// =====================  proxy 监听数组 结束  ======================

// =====================  defineProperty 监听对象开始  ======================
console.log('=====================  defineProperty 监听对象开始  ======================')

const obj2 = {};

Object.defineProperty(obj2, 'name', {
    get() {
        console.log('访问 name')
        return obj2._name;
    },
    set(value) {
        console.log('set name');
        obj2._name = value;
    }
});
obj2.name = '修改name';
console.log('obj2.name', obj2.name);
obj2.age = '修改age';
console.log('obj2.age', obj2.age);



console.log('=====================  defineProperty 监听对象结束  ======================')
// =====================  defineProperty 监听对象结束  ======================